package app

import (
	"context"
	"github.com/sirupsen/logrus"
	"go-iot-gateway/internal/channel"
	channel_providor "go-iot-gateway/internal/channel/providor"
	"go-iot-gateway/internal/conf_table"
	"go-iot-gateway/internal/logger"
	"go-iot-gateway/internal/storage"
	sys_config "go-iot-gateway/internal/sys/config"
	sys_runtime "go-iot-gateway/internal/sys/runtime"
	"go-iot-gateway/internal/web"
)

func initConfiguration(serverConfig *sys_config.SysConfigInfo) error {
	//初始化配置表

	err := conf_table.InitConfTable(serverConfig.HomeDir, serverConfig.ConfigTable)
	if err != nil {
		logrus.Error("配置表数据读取失败")
		return err
	}

	//初始化存储
	err = storage.InitStorage(serverConfig.Storage)
	if err != nil {
		logrus.Error("数据库初始化失败")
		return err
	}

	return nil
}

// 运行所有通道
func runAllChannel() error {
	channelManager := channel.Manager()
	channelList := conf_table.FindAllChannel()
	for _, confInfo := range channelList {

		if !confInfo.IsValid() {
			continue
		}

		chl, err := channel_providor.NewChannel(confInfo.Chl_id)

		if err != nil {
			logrus.Error("通道创建失败 ", err)
			continue
		}

		err = channelManager.RunChannel(chl)
		if err != nil {
			return err
		}
	}

	return nil
}

func Init(ctx context.Context, homeDir string) error {

	serverConfig, err := sys_config.LoadConfig(homeDir)
	if err != nil {
		return err
	}

	//系统环境配置
	sys_runtime.Setting(&serverConfig)

	//日志初始化
	logger.InitLogger(&serverConfig)

	err = initConfiguration(&serverConfig)
	if err != nil {
		return err
	}

	//初始化通道管理器
	channel.InitManager(ctx)

	return nil
}

func Start() error {

	//fmt.Print("=====start gateway=====\n")
	err := runAllChannel()
	if err != nil {
		return err
	}

	//fmt.Print("=====start web endpoint====\n")
	web.StartWebApp()

	return nil
}

func Shutdown(ctx context.Context) error {

	if channel.Manager() != nil {
		channel.Manager().CloseAllChannel()
	}

	storage.CloseStorage()

	web.CloseWebApp(ctx)

	return nil
}
